<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.6.8/angular.min.js"></script>
  </head>
  <body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <h1>{{indexName}}</h1>
      <!-- 自定义组件 -->
      <hello></hello>
    </div>

    <script>
      var app = angular.module("myApp", []);
      app.controller("myCtrl", function ($scope) {
        $scope.indexName = "主页";
      });
      // 第一个组件
      app.component("hello", {
        template: `
            <div>
                <h3>Hello</h3>
                <div>{{$ctrl.parentIndex}}</div>
                <div>子组件数据:{{$ctrl.childIndex}}</div>
                <button ng-click="$ctrl.callChild()">子组件方法</button>
                <world 
                    parent-data="$ctrl.parentIndex"
                    call-parent="$ctrl.callParent()"
                ></world>
            </div>
        `,
        controller: function ($scope) {
          this.$onInit = function () {
          };
          this.parentIndex = 0;
          this.callParent = function () {
            console.log("haha");
            this.parentIndex++;
          };
          // 父组件改变子组件数据
          this.callChild = function () {
            $scope.$$childTail.$ctrl.callChild();
            // 获取到子组件相关的属性
            this.childIndex = $scope.$$childTail.$ctrl.childIndex;
          }
        },
      });
      // 第二个组件
      app.component("world", {
        template: `
            <div>
                <h4>World</h4>
                <div>{{$ctrl.childIndex}}</div>
                <div>父组件的数据: {{$ctrl.parentData}}</div>
                <button ng-click="$ctrl.callParent()">父组件方法</button>
            </div>
        `,
        bindings:{
            parentData:"=",
            callParent:"&"
        },
        controller: function ($scope) {
          this.$onInit = function () {
            this.parentIndex = this.parentData
            this.callParent = this.callParent
          };
          this.childIndex = 0;
          this.callChild = function () {
            this.childIndex++;
          }
        },
      });
    </script>
  </body>
</html>
